/*
 * @Description: 用户信息
 * @Author: wangqi
 * @Date: 2022-04-18 17:14:43
 * @LastEditTime: 2022-04-21 17:55:20
 */
import { defineStore } from 'pinia';
import { type RouteRecordRaw } from 'vue-router';
import { Storage } from '@/utils/Storage';
import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum';
import { generatorDynamicRouter } from '@/router/generator-router';
import { login } from '@/api/login';
import { getInfo, permmenu } from '@/api/account';

interface UserState {
  token: string;
  name: string;
  avatar: string;
  perms: string[];
  menus: RouteRecordRaw[];
  userInfo: Partial<API.AdminUserInfo>;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: Storage.get(ACCESS_TOKEN_KEY, null),
    name: 'amdin',
    avatar: '',
    perms: [],
    menus: [],
    userInfo: {},
  }),
  getters: {},
  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token ?? '';
      const expire = 7 * 24 * 60 * 60 * 1000;
      Storage.set(ACCESS_TOKEN_KEY, this.token, expire);
    },

    // 登录
    async login(params: API.LoginParams) {
      try {
        const { data } = await login(params);
        this.setToken(data.token);
        return this.afterLogin();
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 登录后获取用户菜单
    async afterLogin() {
      try {
        const [userInfo, { perms, menus }] = await Promise.all([getInfo(), permmenu()]);
        // console.log(userInfo, perms, menus, '登录后获取用户菜单');
        this.perms = perms;
        this.userInfo = userInfo;
        this.avatar = userInfo.headImg;
        // 生成路由
        const generatorResult = generatorDynamicRouter(menus);
        this.menus = generatorResult.menus.filter((item) => !item.meta?.hideInMenu);
        return { menus, perms, userInfo };
      } catch (error) {
        console.log('获取用户信息 | 菜单列表 失败!');
      }
    },
  },
});
